package com.zhihuichongcheng.application.ui.mine;

import android.Manifest;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.smartlib.cmnObject.util.AppUtil;
import com.smartlib.cmnObject.util.DeviceUtil;
import com.smartlib.cmnObject.util.DialogUtil;
import com.smartlib.cmnObject.util.GsonUtil;
import com.smartlib.cmnObject.util.LogUtil;
import com.smartlib.cmnObject.util.ToastOpt;
import com.xiaomi.mipush.sdk.MiPushClient;
import com.yunkeshuzhi.common.log.SSLog;
import com.zhihuichongcheng.application.R;
import com.zhihuichongcheng.application.base.BaseActivity;
import com.zhihuichongcheng.application.bean.mine.UserBean;
import com.zhihuichongcheng.application.im.DemoApplication;
import com.zhihuichongcheng.application.im.DemoHelper;
import com.zhihuichongcheng.application.net.HttpCallback;
import com.zhihuichongcheng.application.ui.main.activity.MainActivity;
import com.zhihuichongcheng.application.util.DialogUtils;

import java.util.HashMap;
import java.util.List;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

import static com.zhihuichongcheng.application.constant.NetworkAPI.Login;

/**
 * 注册 Created by 3water on 2016/10/24.
 */
@RuntimePermissions
public class LoginActivity extends BaseActivity {
    private EditText mEtUsername, mEtPassword;
    private TextView mTvLogin, mTvVersion;
    private long mPressedTime;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        isStartAnimation = false;
    }

    private void initView() {

        setStatusBarDarkMode();
//        PermissionUtil.hasPermissionInManifest(this, Manifest.permission.CAMERA);
        mEtUsername = (EditText) findViewById(R.id.username);
        mEtUsername.setText(spUtil.getString("username"));
        mEtPassword = (EditText) findViewById(R.id.password);
        mTvLogin = (TextView) findViewById(R.id.login);
        mTvLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String usernameStr = mEtUsername.getText().toString().trim();
                final String passwordStr = mEtPassword.getText().toString().trim();
                if (TextUtils.isEmpty(usernameStr) || TextUtils.isEmpty(passwordStr)) {
                    ToastOpt.createToast(mContext, "用户名或者密码为空");
                } else {
                    DialogUtil.showLoadDiadlog(mContext);
                    LoginActivityPermissionsDispatcher.loginWithPermissionCheck(LoginActivity.this, usernameStr, passwordStr);
//                    login(usernameStr, passwordStr);
                }
            }
        });

        mTvVersion = (TextView) findViewById(R.id.tv_version);
        mTvVersion.setText("版本号 : " + AppUtil.getVersionName(this));

        mEtUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    String password = mEtPassword.getText().toString();
                    if (!TextUtils.isEmpty(password)) {
                        mTvLogin.setEnabled(true);
                        mTvLogin.setTextColor(getResources().getColor(R.color.white));
                    } else {
                        mTvLogin.setEnabled(false);
                        mTvLogin.setTextColor(getResources().getColor(R.color.color_50_white));
                    }
                } else {
                    mTvLogin.setEnabled(false);
                    mTvLogin.setTextColor(getResources().getColor(R.color.color_50_white));
                }
            }
        });

        mEtPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    String username = mEtUsername.getText().toString();
                    if (!TextUtils.isEmpty(username)) {
                        mTvLogin.setEnabled(true);
                        mTvLogin.setTextColor(getResources().getColor(R.color.white));
                    } else {
                        mTvLogin.setEnabled(false);
                        mTvLogin.setTextColor(getResources().getColor(R.color.color_50_white));
                    }
                } else {
                    mTvLogin.setEnabled(false);
                    mTvLogin.setTextColor(getResources().getColor(R.color.color_50_white));
                }
            }
        });

    }


    /***
     * 登陆
     */
    @NeedsPermission({Manifest.permission.READ_PHONE_STATE, Manifest.permission.CAMERA})
    void login(final String username, final String password) {
        final HashMap<String, String> params = new HashMap<>();
        params.put("mobile", username);
        params.put("password", password);
        String reg = MiPushClient.getRegId(mContext);
        if (!TextUtils.isEmpty(reg)) {
            params.put("regID", MiPushClient.getRegId(mContext));
            SSLog.d("==regId==" + MiPushClient.getRegId(mContext));
        } else {
            params.put("regID", "");
        }
        params.put("deviceId", DeviceUtil.getDeviceId(mContext) + username);
        mManager.post(Login, new HttpCallback() {
            @Override
            public void onSuccess(int code, final String value, String msg) {
                if (code == 1) {
                    final UserBean bean = GsonUtil.praseFromStringToBean(value, UserBean.class);
                    String aliasStr = DeviceUtil.getDeviceId(mContext) + username;
                    MiPushClient.setAlias(getApplicationContext(), aliasStr, null);
                    String userName = bean.getEasemobNumber();
//                    onLoginSuccess(userName, password, value, bean);
                    //TODO 登录环信
                    LoginEmServer(userName, username, password, value, bean);
                } else {
                    ToastOpt.createToast(mContext, msg);
                    DialogUtil.dismiss(mContext);
                }

            }

            @Override
            public void onFailure(String value) {
                spUtil.putString("user", "");
                app.setUser(null);
                DialogUtil.dismiss(mContext);
                ToastOpt.createToast(mContext, "登录失败");
            }
        }, params);


    }

    private void LoginEmServer(String emAccount, final String username, final String password,
                               final String userJson, final UserBean bean) {
        EMClient.getInstance().login(emAccount, password, new EMCallBack() {//回调
            @Override
            public void onSuccess() {
                onLoginSuccess(username, password, userJson, bean);
            }


            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String message) {
                loginOut();
                spUtil.putString("user", "");
                app.setUser(null);
                DialogUtil.dismiss(mContext);
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        ToastOpt.createToast(mContext, "登录聊天服务器失败！");
                    }
                });

                LogUtil.logD("登录聊天服务器失败！" + code + message);
            }
        });
    }

    private void onLoginSuccess(String username, String password, String userJson, UserBean bean) {
        spUtil.putString("username", username);
        spUtil.putString("password", password);
        spUtil.putString("user", userJson);
        List<UserBean> list = bean.getFriends();
        for (int i = 0; i < list.size(); i++) {
            UserBean info = list.get(i);
            spUtil.putObject(info.getEasemobNumber(), info);
        }
        spUtil.putObject(bean.getEasemobNumber(), bean);
        app.setUser(bean);

        EMClient.getInstance().groupManager().loadAllGroups();
        EMClient.getInstance().chatManager().loadAllConversations();
        boolean updatenick = EMClient.getInstance().updateCurrentUserNick(
                DemoApplication.currentUserNick.trim());
        if (!updatenick) {
            Log.e("LoginActivity", "update current user nick fail");
        }
        DemoHelper.getInstance().getUserProfileManager().asyncGetCurrentUserInfo();
        hideKeyboard(mEtUsername);
        hideKeyboard(mEtPassword);
        startActivity(MainActivity.class);
        finish();
        DialogUtil.dismiss(mContext);
    }

    private void loginOut() {
        EMClient.getInstance().logout(false, new EMCallBack() {//回调
            @Override
            public void onSuccess() {
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String message) {
                LogUtil.logD("登录聊天服务器失败！" + code + message);
            }
        });
    }

    @Override
    public void finish() {
        super.finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            DialogUtils.showAlertDialog(this, "确定退出?", new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    app.exit();
                }
            });
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        LoginActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }


    @OnPermissionDenied(Manifest.permission.READ_PHONE_STATE)
    void showDeniedForDeviceId() {
        DialogUtil.dismiss(mContext);
        Toast.makeText(this, "取消授权", Toast.LENGTH_SHORT).show();
    }

    @OnNeverAskAgain(Manifest.permission.READ_PHONE_STATE)
    void showNeverForDeviceId() {
        DialogUtil.dismiss(mContext);
        DialogUtil.showSimpleAlertDialog(mContext, "正常使用，请在设置中允许应用所有权限");
    }
}
